package com.example.nowcodercommunity.service;

import com.example.nowcodercommunity.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 点赞功能实现
     * @param userId
     * @param entityType
     * @param entityId
     */
    public void like(int userId,int entityType,int entityId,int entityUserId){

        redisTemplate.execute(new SessionCallback<Object>() {
            @Override
            public <K, V> Object execute(RedisOperations<K, V> operations) throws DataAccessException {
                String entityKey = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
                String userKey = RedisKeyUtil.getUserLikeKey(entityUserId);

                Boolean isMember = redisTemplate.opsForSet().isMember(entityKey, userId);
                // 事务开始
                operations.multi();
                if(isMember){
                    redisTemplate.opsForSet().remove(entityKey,userId);
                    redisTemplate.opsForValue().decrement(userKey);
                }else{
                    redisTemplate.opsForSet().add(entityKey,userId);
                    redisTemplate.opsForValue().increment(userKey);
                }
                return operations.exec();
            }
        });

    }

    public long getEntityLikeCount(int entityType,int entityId){
        String key = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
        return redisTemplate.opsForSet().size(key);
    }

    public int getEntityLikeStatus(int userId,int entityType,int  entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey,userId) ? 1 : 0;
    }

    public int getUserLikeCount(int userId){
        String userKey = RedisKeyUtil.getUserLikeKey(userId);
        Integer count = (Integer) redisTemplate.opsForValue().get(userKey);
        return count==null ? 0:count;
    }
}
